package until
import (
	"gintest/core/drive"
	"errors"
	"encoding/json"
	"github.com/satori/go.uuid"
	"strings"
	"gintest/core/config"
	"strconv"
	"gintest/database"
	"github.com/garyburd/redigo/redis"
)
type Token=drive.Token

func ReadToken(key,prefix string) (Token,error){
	key=prefix+key
	t_c_t:=config.Sconfig.Read("token","type")
	
	if t_c_t=="boltdb"{
		data:=drive.BoltdbRead("token",key)
		if data==nil{
			return Token{},errors.New("token is nothing")
		}
		t := Token{}
		err := json.Unmarshal(data, &t)
		if err != nil {
			return Token{},errors.New("token is nothing")
		}
		return t,nil

	}else if t_c_t=="memory" {
		data:=drive.MemoryRead(key)
		if data==nil{
			return Token{},errors.New("token is nothing")
		}
		t := Token{}
		err := json.Unmarshal(data, &t)
		if err != nil {
			return Token{},errors.New("token is nothing")
		}
		return t,nil
	}else if t_c_t=="redis"{
		data,err:=redis.String(database.RedisDB.Do("get",key))
		if err!=nil{
			return Token{},errors.New("token is nothing")
		}
		t := Token{}
		err = json.Unmarshal([]byte(data), &t)
		if err != nil {
			return Token{},errors.New("token is nothing")
		}
		return t,nil
	}else{
		return Token{},errors.New("no token")
	}
}
func PutToken(token Token,prefix string) string{
	t_c_t:=config.Sconfig.Read("token","type")
	ses:=strings.Replace(uuid.NewV4().String(), "-", "", -1 )
	expire,_:= strconv.ParseInt(config.Sconfig.Read("token","expire"), 10, 64)
	if t_c_t=="boltdb"{

		str,_:=json.Marshal(token)
		drive.BoltdbPut("token",prefix+ses,[]byte(str),expire)

	}else if t_c_t=="memory"{
		str,_:=json.Marshal(token)
		drive.MemoryPut(prefix+ses,[]byte(str),expire)
	}else if t_c_t=="redis"{
		str,_:=json.Marshal(token)
		_, _ = database.RedisDB.Do("SET", prefix+ses,str,"EX",strconv.FormatInt(expire,10))
	}

	return ses
}
